package com.tz.util;

import com.tz.bean.Dayprice;
import com.tz.dao.dayprice.IDaypriceMapper;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by hfl on 2017-2-12.
 */

@Component
public class TimingTaskUtil {

    @Resource
    private IDaypriceMapper daypriceMapper;



    //需要声明这个锁
    private Lock lock = new ReentrantLock();

    /**
     * 自动获取金价 每2小时获取一次金价
     */
    @Scheduled(cron = "0 0 0/2 * * ?")  //每2小时
    //@Scheduled(cron = "0/20 * * * * ?")  //每20秒
    public void autoGetGold() {
        lock.lock();//上锁
        try{
            new Thread().sleep(5000);
            List<HashMap<String , Object>> lastRecords = daypriceMapper.getLastRecord();
            daypriceMapper.updateByDeleteCode();
            JSONArray arr = WebCrawlers.getDayGoldPrice();
            HashMap map = null;
            Double fetchPrice = 0.0;
            String fetchRemark = "";
            Dayprice dayprice = new Dayprice();
            for(int i=0,len=arr.size();i<len;i++){
                JSONObject obj = (JSONObject) arr.get(i);
                fetchPrice = obj.getDouble("price");
                fetchRemark = obj.getString("remark");
                dayprice.setPrice(fetchPrice);
                dayprice.setName(fetchRemark);
                if(lastRecords.size()>0){
                    for(int j=0,leng=lastRecords.size();j<leng;j++){
                        map = lastRecords.get(j);
                        String name = (String) map.get("name");
                        if(name.equals(fetchRemark)){
                            Double d = (Double) map.get("price");
                            Double c = fetchPrice;
                            if((d-c)/d >=0.05 || (c-d)/d>=0.05 ){
                                dayprice.setIsError("002");//异常
                            }else{
                                dayprice.setIsError("001");
                            }
                        }
                    }
                }else{
                    dayprice.setIsError("001");
                }

                dayprice.setCreateTime(new Date());
                daypriceMapper.save(dayprice);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally{
            lock.unlock();//解锁
        }
    }






}
